﻿using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using Jungle.Code.DAL;
using Jungle.Code.BLL;
using Jungle.Code.Core;
using Jungle.Code.Utils;

using Jungle.Prodamo.PriceManager;
using Jungle.Prodamo.AdvertManager;
using Jungle.Prodamo.MostNeedFunctions;
using Jungle.Prodamo.Core;
using Jungle.Prodamo.PaySystem;

public partial class User : BaseUserModule
{
    SessionKeeper thisSession = new SessionKeeper();
    protected override void OnInit(EventArgs e)
    {
        btn_Upload.PostBackUrl = Request.RawUrl;
        //btn_parse.PostBackUrl = Request.RawUrl;
        thisSession.SessionId = Session.SessionID.ToString();
        thisSession.GetData();

        if (thisSession.UserId != -1)
        {
            tr_Email.Visible = false;
            tr_FastKey.Visible = false;
            tr_Password.Visible = false;

            if (Request["cmd"] != null)
            {
                switch (Request["cmd"])
                {
                    case "Add":
                        {
                            tbl_add.Visible = true;
                            break;
                        }
                }
            }
        }

        if (Request["cmd"] == null)
        {
            if (Request["Id"] == null)
            {
                tbl_add.Visible = false;
                CatTree1.Visible = true;
                hp_home.Visible = false;
            }
            else
            {
                div_freshEnter.InnerHtml = "Заполните ";
                span_end.InnerHtml = "(в первой колонке для всех строк укажите номер " + Request["Id"].ToString() + ")";            
            }

        }
        else
        {
            switch (Request["cmd"])
            {
                case "Add":
                    {
                        tbl_add.Visible = true;
                        break;
                    }
            }
        }

        base.OnInit(e);
    }

    protected HtmlTextWriter GetByCategory(HtmlTextWriter writer)
    {
        int userId = thisSession.UserId;
        Category cats = new Category();
        cats.CategoryId = Convert.ToInt32(Request["Id"]);
        cats.GetById();
        List<Category> CatList1 = cats.GetChilds();
        if (CatList1.Count == 0)
        {
            PriceList1.Visible = true;
            PriceList1.GetBy = 1;
            PriceList1.iId = cats.CategoryId;
        }
        else
        {
            tbl_add.Visible = false;
            // start render span tag
            writer.AddAttribute(HtmlTextWriterAttribute.Id, "price_body");
            writer.RenderBeginTag(HtmlTextWriterTag.Span);

            writer.AddAttribute("class", "advm_table");
            writer.RenderBeginTag(HtmlTextWriterTag.Table);
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            writer.AddAttribute("class", "advm_td");
            writer.AddAttribute("colspan", "2");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("Прайс-листы");
            writer.RenderEndTag();
            writer.RenderEndTag();

            Category cat;
            int i = 0;
            while (i < CatList1.Count)
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Tr);
                writer.RenderBeginTag(HtmlTextWriterTag.Td);

                writer.AddAttribute(HtmlTextWriterAttribute.Href, UrlHelper.GetSiteUrl() + "/ru/price.aspx?Id=" + CatList1[i].CategoryId.ToString());
                writer.AddAttribute("style", "font-size: 12px; text-decoration: none;");
                writer.RenderBeginTag(HtmlTextWriterTag.A);
                writer.Write(CatList1[i].Name);
                writer.RenderEndTag();

                writer.RenderEndTag();
                writer.RenderEndTag();

                i++;
            }
            writer.RenderEndTag();

            // end render span tag "price_body"
            writer.RenderEndTag();
        }
        return writer;
    }
    protected HtmlTextWriter GetById(HtmlTextWriter writer)
    {
        CatTree1.Visible = false;
        PriceList1.Visible = true;
        PriceList1.GetBy = 2;
        PriceList1.iId = Convert.ToInt32(Request["pId"]);
        return writer;
    }
    protected override void Render(HtmlTextWriter writer)
    {
        if (Request["pId"] != null)
        {
            GetById(writer);
        }
        if (Request["Id"] != null) GetByCategory(writer);
        if (Request.QueryString["cmd"] == "myprice")
        {
            tbl_add.Visible = false;
            PriceList1.Visible = true;
            PriceList1.GetBy = 5;
            PriceList1.iId = thisSession.UserId;
        }
        base.Render(writer);
    }
    
    protected void Upload(object sender, EventArgs e)
    {
        ccJoin.ValidateCaptcha(tb_Cap.Text);
        if (thisSession.UserId != -1)
        {
            InsertPrice();
        }
        else 
        {
            if (tb_FastKey.Text.Trim().Length == 6)
            {
                FastEnter();
            }
            else
            {
                UserManager um = new UserManager();
                um.NickName = tb_Email.Text;
                um.Password = Functions.getMd5Hash(tb_Password.Text.Trim());

                if (um.Login())
                {
                    thisSession.SessionId = Session.SessionID.ToString();
                    thisSession.UserId = um.UserId;
                    thisSession.UserLogin = um.NickName;
                    thisSession.AdminLogin = "none";

                    thisSession.Create();

                    InsertPrice();
                }
                else
                {
                    if (!um.CheckNickName())
                    {
                        ValidBlock.InnerHtml = "Пользователь с таким Email уже зарегистрирован. Если это вы, то вы просто ввели неверный пароль.";
                    }
                    else
                    {
                        FastRegister();
                        if (um.Login())
                        {
                            thisSession.SessionId = Session.SessionID.ToString();
                            thisSession.UserId = um.UserId;
                            thisSession.UserLogin = um.NickName;
                            thisSession.AdminLogin = "none";

                            thisSession.Create();

                            InsertPrice();
                        }
                    }
                }                
            }
        }
            
    }
    protected void InsertPrice()
    {
        if (fu_Price.HasFile && ccJoin.UserValidated)
        {
            string SavePath = Server.MapPath("UserFiles/Prices/" + thisSession.SessionId + "_" + fu_Price.FileName);
            fu_Price.PostedFile.SaveAs(SavePath);

            OleDbConnection ExcelConnection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + SavePath + ";Extended Properties=Excel 8.0;");
            DataSet ExcelDataSet = new DataSet();
            OleDbCommand command = new OleDbCommand("SELECT * FROM [Лист1$]", ExcelConnection);
            OleDbDataReader reader = null;
            command.Connection.Open();
            reader = command.ExecuteReader();
            while (reader.Read())
            {
                if (reader[0] == DBNull.Value) break;
                Price price = new Price();
                price.UserId = thisSession.UserId;

                UserManager u = new UserManager();
                u.UserId = thisSession.UserId;
                u.GetById();

                price.Vip = u.Vip;
                price.CategoryId = Convert.ToInt32(reader[0]);
                price.Code = reader[1].ToString().Trim();

                Producer producer = new Producer();
                producer.Title = reader[2].ToString().Trim();
                producer.GetByTitle();
                if (producer.ProducerId == 0)
                {
                    producer.Title = reader[2].ToString().Trim();
                    producer.WebSite = "http://website.com";
                    producer.Logo = "~/UserFiles/1px.gif";
                    producer.Add();

                    PBC pbc = new PBC();
                    pbc.ProducerId = producer.ProducerId;
                    pbc.CategoryId = price.CategoryId;
                    pbc.Add();
                }
                price.ProducerId = producer.ProducerId;

                Model model = new Model();
                model.Title = reader[3].ToString().Trim();
                model.GetByTitle();
                if (model.ModelList.Count == 0)
                {
                    model.ProducerId = price.ProducerId;
                    model.Title = reader[3].ToString().Trim();
                    model.ImageUrl = "~/UserFiles/1px.gif";
                    model.Add();

                    price.ModelId = model.ModelId;

                }
                else
                {
                    bool valid = false;
                    foreach (Model md in model.ModelList)
                    {
                        if (md.ProducerId == producer.ProducerId)
                        {
                            valid = true;
                            price.ModelId = md.ModelId;
                            break;
                        }
                    }
                    if (!valid)
                    {
                        model.ProducerId = price.ProducerId;
                        model.Title = reader[3].ToString().Trim();
                        model.ImageUrl = "~/UserFiles/1px.gif";
                        model.Add();

                        price.ModelId = model.ModelId;
                    }
                }
                price.Description = reader[4].ToString().Trim();

                price.Guarant = 0;
                string guarant = reader[5].ToString().Trim();
                if (guarant.Length == 0) price.Guarant = 0;
                else price.Guarant = Convert.ToInt32(guarant);

                if (reader[7] == DBNull.Value) price.PriceGrnOpt = 0;
                else price.PriceGrnOpt = Convert.ToDouble(reader[7]);

                if (reader[6] == DBNull.Value) price.PriceGrnRozn = 0;
                else price.PriceGrnRozn = Convert.ToDouble(reader[6]);

                if (reader[8] == DBNull.Value) price.PriceUeRozn = 0;
                else price.PriceUeRozn = Convert.ToDouble(reader[8]);

                if (reader[9] == DBNull.Value) price.PriceUeOpt = 0;
                else price.PriceUeOpt = Convert.ToDouble(reader[9]);

                switch (reader[10].ToString().Trim())
                {
                    case "Да": price.Have = 0; break;
                    case "Нет": price.Have = 1; break;
                    case "Заказ": price.Have = 2; break;
                    default: price.Have = 1; break;
                }
                price.Add();
            }
            reader.Close();
            command.Connection.Close();
            Response.Redirect(UrlHelper.GetSiteUrl() + "/ru/price.aspx?cmd=myprice");
        }
        else
        {
            ValidBlock.InnerHtml = "Выв вели неверный проверочный код";
        }
        
    }













    protected void FastRegister()
    {
        if (tb_Email.Text.IndexOf("@") != -1)
        {
            UserManager um = new UserManager();
            um.NickName = tb_Email.Text.Trim();

            string password = tb_Password.Text.Trim();
            um.Fname = "Безымянный";
            um.Oname = "Безымянный";
            um.Iname = "Безымянный";
            um.Email = um.NickName;
            um.Sex = true;
            um.Organization = um.NickName;
            um.Edrpou = "NONE";
            um.WorkTime = "NONE";
            um.Web = "NONE";
            um.Logo = "~/Images/1px.gif";
            um.Map = "~/Images/1px.gif";
            um.Deliver = "";
            um.Credit = "";
            um.Country = "1";
            um.Zip = "00000";
            um.City = "1";
            um.Address = "нет";
            um.Phone = "";
            um.Faks = "";
            um.BirthDay = DateTime.Now;
            um.Password = Functions.getMd5Hash(password);
            um.UsertType = false;
            um.FastKey = GetRandom("");
            um.Add();

            Account acc = new Account();
            acc.CreateAccount(um.UserId);

            string body = "Вы были зарегистрированы на prodamo.com. Данные для доступа: Email:" + um.NickName + ". Password: " + password + ". Ключ быстрого доступа: " + um.FastKey;
            um.SendEmail(um.Email, "prodamo.com: подтверждение регистрации", body);

        }
        else ValidBlock.InnerHtml = "Вы ввели некорректный Email";
    }
    protected void FastEnter()
    {
        UserManager um = new UserManager();
        um.FastKey = tb_FastKey.Text;
        um.GetByFastKey();

        if (um.UserId != 0)
        {
            if (um.Login())
            {
                thisSession.UserId = um.UserId;
                thisSession.SessionId = Session.SessionID.ToString();
                thisSession.UserLogin = um.NickName;
                thisSession.AdminLogin = "none";
                thisSession.Create();

                InsertPrice();
            }
        }
        else
        {
            ValidBlock.InnerHtml = "Вы ввели некорректный код";
        }
    }
    protected string GetRandom(string str)
    {
        string mask = "1234567890qwertyuiopasdfghjklzxcvbnm";
        System.Random rnd = new Random();
        for (int i = 0; i < 6; i++)
        {
            str += mask[rnd.Next(0, 35)];
        }
        return str;
    }
    protected void Parse()
    {
        System.IO.StreamReader reader = new System.IO.StreamReader(Server.MapPath("2.txt"), Encoding.GetEncoding(1251));
        int ParentId = 22;
        int reParentId = 0;
        while (true)
        {
            string line = reader.ReadLine();
            if (line == null) break;

            if (line.StartsWith("*")) ParentId++;
            else
            {
                bool re = false;
                Category cat = new Category();

                if (line.StartsWith(" "))
                {
                    cat.ParentId = reParentId;
                    re = true;
                }
                else cat.ParentId = ParentId;
                line = line.Substring(0, line.IndexOf("("));


                cat.Name = line.Trim();
                cat.Alias = line.Trim();
                cat.ImageUrl = "~/Images/1px.gif";
                cat.IsVisible = true;
                cat.Add();

                if (!re)
                    reParentId = cat.CategoryId;
            }
        }
        reader.Close();
    }

}
